import os
import sys
import pandas as pd

# ✅ 设置路径
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))
if BASE_DIR not in sys.path:
    sys.path.insert(0, BASE_DIR)

from src.weighting.entropy_weight import entropy_weight
from src.weighting.pca_weight import pca_weight
from src.weighting.independence_weight import independence_weight
from src.weighting.combine_weights import combine_entropy_and_independence_weights
from src.weighting.rsr_ranking import rsr_ranking
from src.weighting.topsis_rank import topsis_ranking
from src.weighting.generate_level_scores import generate_level_scores
from src.weighting.attach_country_attributes import attach_country_attributes
# ✅ 路径设置
data_dir = os.path.join(BASE_DIR, "data", "4_weighting_modeling")
result_dir = os.path.join(data_dir, "weights_result")
os.makedirs(result_dir, exist_ok=True)

input_file = os.path.join(data_dir, "indicators_binned_dynamic_quantile.csv")
df = pd.read_csv(input_file)
meta_cols = ['序号', '国名En', '国名Ch', '年份']
indicator_cols = [col for col in df.columns if col not in meta_cols]

# ✅ 权值计算方法交互
print("请选择权值计算方法：")
print("1️⃣ PCA 主成分分析法")
print("2️⃣ 熵权法 Entropy")
print("3️⃣ 独立性权重法 Independence")
print("4️⃣ 综合权重法 Combine（熵权 + 独立性）")
method_map = {'1': 'pca', '2': 'entropy', '3': 'independence', '4': 'combine'}

weight_choice = input("👉 请输入对应数字（1/2/3/4）进行选择：").strip()
if weight_choice not in method_map:
    print("❌ 输入无效，请重新运行程序。")
    sys.exit(1)

selected_method = method_map[weight_choice]
print(f"✅ 已选择权值计算方法：{selected_method}")

# ✅ 权值计算
if selected_method == 'pca':
    weights = pca_weight(df, indicator_cols)
elif selected_method == 'entropy':
    weights = entropy_weight(df, indicator_cols)
elif selected_method == 'independence':
    weights = independence_weight(df, indicator_cols)
else:
    entropy_w = entropy_weight(df, indicator_cols)
    independence_w = independence_weight(df, indicator_cols)
    weights = combine_entropy_and_independence_weights(entropy_w, independence_w)

weights_df = pd.DataFrame({'指标': weights.index, '权值': weights.values})
weight_file = os.path.join(result_dir, f"indicator_weights_{selected_method}.csv")
weights_df.to_csv(weight_file, index=False, encoding='utf-8-sig')
print(f"📁 权值结果已保存：{weight_file}")

# ✅ 计算一级维度得分和权重
df_level, level_weights, level_score_file = generate_level_scores(df, weights, meta_cols, result_dir, selected_method)
print("📊 六维一级指标加权得分和权重计算完成")

# ✅ 评价方法交互
print("\n请选择评价方法：")
print("1️⃣ RSR")
print("2️⃣ TOPSIS")
eval_choice = input("👉 请输入（1/2）：").strip()

result_df = None  # 初始化排序结果变量
if eval_choice == '1':
    output_path = os.path.join(result_dir, f"RSR_评分排序_{selected_method}.csv")
    result_df = rsr_ranking(df_level.copy(), level_weights, output_path, num_levels=4)
    print(f"✅ RSR 排序结果已保存为：{output_path}")
    result_df = pd.read_csv(output_path)
elif eval_choice == '2':
    output_path = os.path.join(result_dir, f"TOPSIS_评分排序_{selected_method}.csv")
    result_df = topsis_ranking(df_level.copy(), level_weights, output_path, num_levels=4)
    print(f"✅ TOPSIS 排序结果已保存为：{output_path}")
    result_df = pd.read_csv(output_path)
else:
    print("❌ 无效输入，请重新运行程序")
    sys.exit(1)


attach_country_attributes(result_df, output_path, data_dir)


